class Compiler {
  constructor(vm) {
    this.el = vm.$el;
    this.vm = vm;
    this.compile(this.el);
  }
  // 编译模板，处理文本节点和火元素节点
  compile(el) {
    const childNodes = el.childNodes;
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        // 处理文本节点
        this.compileText(node);
      } else if (this.isElementNode(node)) {
        // 处理元素节点
        this.compileElement(node)
      }
      // 如果node有子节点，则地柜调用compile
      if (node.childNodes?.length) {
        this.compile(node);
      }
    });
  }
  // 编译元素节点，处理指令
  compileElement(node) {
    // 遍历所有属性节点node.attributes
    Array.from(node.attributes).forEach(attr => {
      // 判断是否为指令
      let attrName = attr.name;
      if (this.isDirective(attrName)) {
        // v-text --> text  v-html  v-on:click="clickMethod"
        attrName = attrName.substr(2); // on:click
        let key = attr.value; //clickMethod
        if (attrName.startsWith('on')) {
          this.updateEvent(node, key, attrName.replace('on:', ''));
          return;
        }
        this.update(node, key, attrName);
      }
    });
  }
  update(node, key, attrName) {
    const attrNames = attrName.split(':');
    const updateFn = this[`_${attrNames[0]}Updater`];
    updateFn && updateFn(node, this.vm[key], attrNames[0] === 'on' ? attrNames[1] : key);
  }
  updateEvent(node, eventHandler, eventName) {
    node.addEventListener(eventName, (e) => this.vm[eventHandler](e));
  }
  // 处理v-html指令
  _htmlUpdater = (node, value, key) => {
    node.innerHTML = value;
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue;
    })
  }
  // 处理v-text指令
  _textUpdater = (node, value, key) => {
    node.textContent = value;
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue;
    })
  }
  // 处理v-model
  _modelUpdater = (node, value, key) => {
    node.value = value;
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue;
    });
    // 双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value;
    })
  }
  // 编译文本节点，处理差值表达式
  compileText(node) {
    // {{ msg }}
    const reg = /{{(.+?)}}/;
    const value = node.textContent;
    if (reg.test(value)) {
      const key = RegExp.$1.trim();
      node.textContent = value.replace(reg, this.vm[key]);

      // 创建watcher对象，当数据改变的时候更新视图
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue;
      })
    }
  }
  // 判断元素属性是否为指令
  isDirective = (attrName) =>
    attrName.startsWith('v-');
  // 判断节点是否为文本节点
  isTextNode = (node) =>
    node.nodeType === 3
  // 判断节点是否为元素节点
  isElementNode = (node) =>
    node.nodeType === 1
}